const express = require('express');
const router = express.Router();
const Favorite = require('../models/Favorite');
const auth = require('../middleware/auth');
const mongoose = require('mongoose');

// 调试中间件
router.use((req, res, next) => {
  console.log('❤️ Favorites route:', req.method, req.url);
  next();
});

// 获取用户收藏列表
router.get('/', auth, async (req, res) => {
  try {
    console.log('📥 Getting favorites for user:', req.userId);
    
    const favorites = await Favorite.find({ userId: req.userId })
      .populate({
        path: 'postId',
        populate: {
          path: 'author',
          select: 'username avatar'
        }
      })
      .sort({ createdAt: -1 });
    
    console.log(`✅ Found ${favorites.length} favorites`);
    
    // 过滤掉可能为空的postId
    const validFavorites = favorites.filter(fav => fav.postId !== null);
    
    res.json(validFavorites.map(fav => fav.postId));
  } catch (error) {
    console.error('❌ Get favorites error:', error);
    res.status(500).json({ error: '获取收藏失败' });
  }
});

// 添加收藏
router.post('/:postId', auth, async (req, res) => {
  try {
    const postId = req.params.postId;
    console.log('➕ Adding favorite - User:', req.userId, 'Post:', postId);

    // 验证postId格式
    if (!mongoose.Types.ObjectId.isValid(postId)) {
      return res.status(400).json({ error: '无效的帖子ID' });
    }

    // 检查是否已经收藏
    const existingFavorite = await Favorite.findOne({
      userId: req.userId,
      postId: postId
    });

    if (existingFavorite) {
      console.log('⚠️ Already favorited');
      return res.status(400).json({ error: '已收藏过该帖子' });
    }

    const favorite = new Favorite({
      userId: req.userId,
      postId: postId
    });
    
    await favorite.save();
    console.log('✅ Favorite added successfully');
    
    res.json({ 
      message: '收藏成功',
      favoriteId: favorite._id 
    });
  } catch (error) {
    console.error('❌ Add favorite error:', error);
    if (error.code === 11000) {
      return res.status(400).json({ error: '已收藏过该帖子' });
    }
    res.status(500).json({ error: '收藏失败' });
  }
});

// 取消收藏
router.delete('/:postId', auth, async (req, res) => {
  try {
    const postId = req.params.postId;
    console.log('➖ Removing favorite - User:', req.userId, 'Post:', postId);

    // 验证postId格式
    if (!mongoose.Types.ObjectId.isValid(postId)) {
      return res.status(400).json({ error: '无效的帖子ID' });
    }

    const result = await Favorite.findOneAndDelete({
      userId: req.userId,
      postId: postId
    });

    if (!result) {
      console.log('⚠️ Favorite not found');
      return res.status(404).json({ error: '未找到收藏记录' });
    }
    
    console.log('✅ Favorite removed successfully');
    res.json({ message: '取消收藏成功' });
  } catch (error) {
    console.error('❌ Remove favorite error:', error);
    res.status(500).json({ error: '取消收藏失败' });
  }
});

// 检查收藏状态
router.get('/check/:postId', auth, async (req, res) => {
  try {
    const postId = req.params.postId;
    console.log('🔍 Checking favorite status - User:', req.userId, 'Post:', postId);

    // 验证postId格式
    if (!mongoose.Types.ObjectId.isValid(postId)) {
      return res.status(400).json({ error: '无效的帖子ID' });
    }

    const favorite = await Favorite.findOne({
      userId: req.userId,
      postId: postId
    });
    
    console.log('✅ Favorite check result:', !!favorite);
    res.json({ isFavorited: !!favorite });
  } catch (error) {
    console.error('❌ Check favorite error:', error);
    res.status(500).json({ error: '检查收藏状态失败' });
  }
});

module.exports = router;